# -*-coding:utf-8 -*-
import requests
from lxml import etree
import datetime
import pymysql
'最近比赛爬取（功能17）和比赛时间比例（功能18）'


# 获取页面数据
def getPageInfo():
    url = 'https://www.huya.com/m'
    # 返回一个比赛数据的数组
    matchArr = []
    # 返回比赛时间的统计
    matchTimeDict = {}
    response = requests.get(url=url)
    response.encoding = 'utf-8'
    tree = etree.HTML(response.text)
    index = 0
    while index < 5:
        path = "//div[@class='schedule-box']/ul[" + str(index + 1) + "]/li"
        list = tree.xpath(path)
        for li in list:
            # 直播间名
            liveName = li.xpath("./h3/a/text()")[0].strip()
            # 如果有两个队伍进行比赛，就将比赛简介中加入两支队伍的名字
            matchIntro = li.xpath(
                "./div/div[@class = 'detail-cnt']/span[2]/text()")[0].strip()
            teamA = li.xpath(
                "./div/div[@class = 'detail-team detail-team_A']/span/text()")
            teamB = li.xpath(
                "./div/div[@class = 'detail-team detail-team_B']/span/text()")
            if len(teamA) != 0:
                matchIntro = matchIntro + '( ' + teamA[0].strip(
                ) + ' VS ' + teamB[0].strip() + " )"
            # 只有时间，没有日期
            time = li.xpath(
                "./div/div[@class = 'detail-cnt']/span[1]/text()")[0].strip()
            # 日期+时间
            date = (datetime.datetime.now() + datetime.timedelta(days=index)
                    ).strftime("%Y-%m-%d ") + time
            # 比赛状态
            state = li.xpath(
                "./div/div[@class = 'detail-cnt']/a/text()")[0].strip()
            if state == '预订':
                state = '未开始'
            # 记录进比赛信息里面
            matchDict = {
                "liveName": liveName,
                "matchIntro": matchIntro,
                "date": date,
                "state": state
            }
            matchArr.append(matchDict)
            # 记录到时间统计表内
            if time not in matchTimeDict:
                matchTimeDict[time] = 1
            else:
                matchTimeDict[time] = matchTimeDict[time] + 1
        index = index + 1
    return matchArr, matchTimeDict


# 创建MySQL连接函数（当做固定）
def getMysqlConn():
    conn = pymysql.connect(host='106.13.194.7',
                           port=3306,
                           user='rdsroot',
                           password='abc123456',
                           db='huya',
                           charset='utf8')
    # 创建操作的游标
    cursor = conn.cursor()
    # 设置字符编码及自动提交
    cursor.execute('set names utf8')  # 固定格式
    cursor.execute('set autocommit=1')
    # 设置自动提交
    return conn, cursor


# 存比赛信息
def saveMatchData(matchArr):
    conn, cursor = getMysqlConn()
    # sql语句
    sql = "insert into t_match (id,liveName,matchIntro,date,state) values(REPLACE(UUID(),'-',''),%s,%s,%s,%s)"
    for match in matchArr:
        add_data = (match["liveName"], match["matchIntro"], match["date"],
                    match["state"])
        # 这里会把sql语句中的%s替换掉
        cursor.execute(sql, add_data)
    print("比赛信息插入数据完成")
    # 关闭连接
    cursor.close()
    conn.close()


# 存比赛时间
def saveTimeData(matchTimeDict):
    conn, cursor = getMysqlConn()
    # sql语句
    sql = "insert into t_matchTime (id,time,count) values(REPLACE(UUID(),'-',''),%s,%s)"
    for key, value in matchTimeDict.items():
        add_data = (key, value)
        # 这里会把sql语句中的%s替换掉
        cursor.execute(sql, add_data)
    print("比赛时间数据插入完成")
    # 关闭连接
    cursor.close()
    conn.close()


if __name__ == '__main__':
    matchArr, matchTimeDict = getPageInfo()
    saveMatchData(matchArr)
    saveTimeData(matchTimeDict)
